const BaseService = require('./base_service.js');
const util = require('../utils/util.js');
const config = require('../config/config.js');
const axios = require('axios');
const QAModel = require('../model/qa_model.js');

class QaService extends BaseService {
    constructor() {
        super();
        this._token = null;
        this._tokenExpireTime = 0;
        this._model = new QAModel();
    }

    /** 问答接口 */
    async ask(userId, question) {
        if (!question || question.trim().length === 0) {
            return { 
                code: 0, 
                result: {
                    answer: '请输入您的问题',
                    references: []
                }
            };
        }

        try {
            // 搜索相关知识
            const context = await this._search(question, 3);
            
            // 构建提示词
            const prompt = this._buildPrompt(question, context);
            
            // 调用LLM API获取回答
            const answer = await this._callLLMApi(prompt);
            
            // 保存对话记录
            await this._saveChat(userId, question, answer.result.answer, context);
            
            return {
                code: 0,
                result: {
                    answer: answer.result.answer,
                    references: context
                }
            };
        } catch (error) {
            console.error('处理问题失败:', error);
            return { 
                code: 1, 
                error: '服务异常，请稍后再试' 
            };
        }
    }

    /** 获取访问令牌 */
    async _getAccessToken() {
        const now = Date.now();
        if (this._token && now < this._tokenExpireTime) {
            return this._token;
        }

        const response = await axios({
            method: 'POST',
            url: config.TOKEN_URL,
            params: {
                grant_type: 'client_credentials',
                client_id: config.QIANFAN_API_KEY,
                client_secret: config.QIANFAN_SECRET_KEY
            }
        });

        this._token = response.data.access_token;
        this._tokenExpireTime = now + (response.data.expires_in - 60) * 1000; // 提前1分钟过期
        return this._token;
    }

    /** 调用LLM API */
    async _callLLMApi(prompt) {
        const token = await this._getAccessToken();
        const response = await axios({
            method: 'POST',
            url: `${config.LLM_URL}?access_token=${token}`,
            data: {
                messages: [{
                    role: "user",
                    content: prompt
                }],
                model: "ERNIE-Bot-4"
            },
            headers: { 'content-type': 'application/json' }
        });
        return {
            code: 0,
            result: {
                answer: response.data.result,
                references: []
            }
        };
    }

    /** 构建提示词 */
    _buildPrompt(question, context) {
        let prompt = '你是一个专业的电力系统问答助手。请根据以下参考资料，回答用户的问题。如果无法从参考资料中找到答案，请基于你的专业知识给出合理的回答。\n\n';
        
        if (context && context.length > 0) {
            prompt += '参考资料：\n';
            context.forEach((item, index) => {
                prompt += `${index + 1}. ${item.title}\n${item.content}\n\n`;
            });
        }
        
        prompt += `用户问题：${question}\n\n请回答：`;
        return prompt;
    }

    /** 保存对话记录 */
    async _saveChat(userId, question, answer, references) {
        const collection = this.db.collection('qa_history');
        await collection.add({
            userId,
            question,
            answer,
            references,
            createTime: this.db.serverDate()
        });
    }

    /** 添加历史记录 */
    async addHistory(userId, data) {
        return await this._model.add({
            USER_ID: userId,
            QUESTION: data.question,
            ANSWER: data.answer,
            REFERENCES: data.references,
            ADD_TIME: this._timestamp(),
            EDIT_TIME: this._timestamp(),
            STATUS: 1
        });
    }

    /** 获取历史记录列表 */
    async getHistory(userId, page, size) {
        return await this._model.getList({
            USER_ID: userId,
            STATUS: 1
        }, '*', { ADD_TIME: 'desc' }, page, size);
    }

    /** 获取历史记录详情 */
    async getHistoryDetail(userId, id) {
        return await this._model.getOne({
            _id: id,
            USER_ID: userId,
            STATUS: 1
        });
    }

    /** 删除历史记录 */
    async deleteHistory(userId, id) {
        return await this._model.del({
            _id: id,
            USER_ID: userId
        });
    }
}

module.exports = QaService; 